package com.aaa.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.*;

/**
 * @program: qy172-jwt
 * @description:
 * @author: 闫克起2
 * @create: 2024-02-22 09:16
 **/
public class JWTUtil {
    private static String sign="qy172-shuaigemv";
    //1.生成token
    public static String createToken(String name, List<String> permissions){
        Map<String,Object> header=new HashMap<String,Object>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        Calendar calendar=Calendar.getInstance();//获取当前时间
        calendar.set(Calendar.HOUR,24); //在当前时间的基础上增加1800秒
        Date expire = calendar.getTime(); //追加1800后获取时间。
        String token = JWT.create().withHeader(header)
                .withIssuedAt(new Date()) //设置token颁发时间
                .withExpiresAt(expire) //设置token失效时间
                .withClaim("name", name) //设置自己的字段--唯一标识
                .withClaim("permissions",permissions) //设置当前用户的权限码
                .sign(Algorithm.HMAC256(sign));
        return token;
    }
    //2.校验令牌
    public static boolean validate(String token){
        try {
            JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    //3.解析令牌
    public static String getName(String token){
        String name = JWT.decode(token).getClaim("name").asString();
        return name;
    }
    //3.解析令牌
    public static List<String> getPermission(String token){
        List<String> list = JWT.decode(token).getClaim("permissions").asList(String.class);
        return list;
    }

}
